package edu.njit.hz278.core.web;

import java.io.IOException;
import java.io.OutputStream;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

/**
 * JSONMapper.
 * 
 * @author Rivers Zhang
 */
public class JSONMapper {
	private static final ObjectMapper mapper = new ObjectMapper();

	/**
	 * Decode `value' to an Object.
	 * 
	 * @param type
	 * @param value
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	public static Object decode(Class<?> type, String value)
			throws JsonParseException, JsonMappingException, IOException {
		return mapper.readValue(value, type);
	}

	/**
	 * Decode `value' to an array of Objects.
	 * 
	 * @param type
	 * @param value
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	public static Object decodeAsArray(Class<?> type, String value)
			throws JsonParseException, JsonMappingException, IOException {
		return mapper.readValue(value, mapper.getTypeFactory()
				.constructArrayType(type));
	}

	/**
	 * Encode `val' to string representation.
	 * 
	 * @param val
	 * @return
	 * @throws JsonGenerationException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	public static String encode(Object val) throws JsonGenerationException,
			JsonMappingException, IOException {
		return mapper.writeValueAsString(val);
	}

	/**
	 * Write the string representation of `value' along with the callback name
	 * `cb' to `out'.
	 * 
	 * @param out
	 * @param value
	 * @param cb
	 * @throws JsonGenerationException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	public static void writeJSONP(OutputStream out, Object value, String cb)
			throws JsonGenerationException, JsonMappingException, IOException {
		String s = (cb == null ? "" : cb).concat("(").concat(encode(value))
				.concat(");");
		out.write(s.getBytes());
	}

	/**
	 * Write the string representation of `value' to `out'.
	 * 
	 * @param out
	 * @param value
	 * @throws JsonGenerationException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	public static void writeJSON(OutputStream out, Object value)
			throws JsonGenerationException, JsonMappingException, IOException {
		mapper.writeValue(out, value);
	}
}
